<script setup>
import { ref, computed } from 'vue';

const products = ref([
  { id: 1, name: '手机', price: 10012, count: 0 },
  { id: 2, name: '零食', price: 200, count: 0 },
  { id: 3, name: '香蕉', price: 300, count: 0 },

]);

const totalAmount = computed(() =>
  products.value.reduce((sum, product) => sum + product.price * product.count, 0)
);

function increaseCount(productId) {
  const product = products.value.find(p => p.id === productId);
  if (product) {
    product.count++;
  }
}

function decreaseCount(productId) {
  const product = products.value.find(p => p.id === productId);
  if (product.count > 0) {
    product.count--;
  }
}
</script>

<template>
  <div class="shopping-cart">
    <h2>购物车</h2>
    <ul class="product-list">
      <li v-for="product in products" :key="product.id" class="product-item">
        <div class="product-info">
          {{ product.name }} - ${{ product.price }} (数量: {{ product.count }})
        </div>
        <div class="product-actions">
          <button @click="decreaseCount(product.id)">-</button>
          <button @click="increaseCount(product.id)">+</button>
        </div>
      </li>
    </ul>

    <hr>

    <h3 class="total">总价: ${{ totalAmount }}</h3>
  </div>
</template>

<style scoped>
.shopping-cart {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.product-list {
  list-style: none;
  padding: 0;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
  padding: 10px 0;
}

.product-info {
  flex: 1;
}

.product-actions {
  display: flex;
  gap: 10px;
}

button {
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

button:disabled {
  background-color: #aaa;
  cursor: not-allowed;
}

.total {
  margin-top: 20px;
}
</style>